<?php

declare(strict_types=1);

namespace App\Hoenix\Listener;

use App\Fastapp\Listener\Event\TgBotJoinGroupEvent;
use App\Fastapp\Model\FastappRobotGroup;
use App\Fastapp\Model\FastappRobotGroupAuth;
use App\Hoenix\Job\IndexKeywordJob;
use App\Hoenix\Job\TgChatInfoJob;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;
use swoole\Coroutine;
use Telegram\Bot\Api;

#[Listener]
class HoenixListener implements ListenerInterface
{
    public function __construct(protected ContainerInterface $container)
    {
    }

    public function listen(): array
    {
        return [
            TgBotJoinGroupEvent::class
        ];
    }

    public function process(object $event): void
    {
        if ($event instanceof TgBotJoinGroupEvent) {
            if ($event->join) $up = ['status' => 1]; else $up = ['status' => 0];
            $auth = FastappRobotGroupAuth::query()->with(['robot', 'group'])->where([
                'source' => 1,
                'group_id' => $event->chat['id'],
                'bot_id' => $event->bot_id
            ])->first();
            $bot = new Api(redis()->hGetAll('bot:' . $event->bot_id)['token']);
            try {
                if (!$auth) {
                    $bot->sendMessage([
                        'chat_id' => FastappRobotGroup::query()->where(['source' => 1, 'group_id' => $event->chat['id']])->value('source_user'),
                        'text' => '💡机器人已退出',
                    ]);
                    return;
                }
                if ($auth->robot->is_admin && $auth->role != 'administrator') {
                    $bot->sendMessage([
                        'chat_id' => $event->tg_id,
                        'text' => '💡机器人已加入,开启管理员权限后自动激活',
                    ]);
                    return;
                }
            } catch (\Throwable) {
                return;
            }
            $up['title'] = $event->chat['title'];
            $up['type'] = $auth->group->type == 3 ? 2 : 1;
            if (!empty($event->chat['username'])) {
                $up['username'] = $event->chat['username'];
                $up['url'] = 'https://t.me/' . $event->chat['username'];
            }
            $up['chat_id'] = $event->chat['id'];
            $up['sort'] = 1;
            $up['status'] = 1;
            $up['is_chat'] = 1;
            fastapp_queue_push(new IndexKeywordJob($up), 'hoenix');
            if (!empty($event->chat['username'])) fastapp_queue_push(new TgChatInfoJob($event->bot_id, $event->chat['username']), 'hoenix');
            if ($auth->robot->is_admin) {
                Coroutine::create(function () use ($event, $bot) {
                    try {
                        $msg = $bot->sendMessage([
                            'chat_id' => $event->chat['id'],
                            'text' => '机器人成功激活(15秒后自动删除)',
                        ]);
                        Coroutine::sleep(15);
                        $bot->deleteMessage([
                            'chat_id' => $event->chat['id'],
                            'message_id' => $msg->messageId
                        ]);
                    } catch (\Throwable $throwable) {
                        sys_notify($throwable->getMessage() . __FILE__);
                        $bot->sendMessage([
                            'chat_id' => FastappRobotGroup::query()->where(['source' => 1, 'group_id' => $event->chat['id']])->value('source_user'),
                            'text' => '💡机器人权限不足：' . $event->chat['username'],
                        ]);
                    }
                });
            }
        }
    }
}
